package de.bloxel.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jme3.export.binary.BinaryExporter;
import com.jme3.export.binary.BinaryImporter;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;

import de.bloxel.core.events.Event;
import de.bloxel.core.events.EventListener;
import de.bloxel.ui.BloxelApplication;

/**
 * responsible for saving and loading the scene graph listens for "SAVE" and "LOAD" events
 * 
 * @author dorer
 * 
 */
public class GameLoader implements EventListener {

  private static final Logger LOG = LoggerFactory.getLogger(GameLoader.class);

  private final BloxelApplication bloxelApplication;

  public GameLoader(final BloxelApplication application) {
    bloxelApplication = application;
  }

  @Override
  public boolean handleEvent(final Event event) {
    if (event.getType().equalsIgnoreCase("LOAD")) {
      final LoadEvent loadEvent = (LoadEvent) event;
      // // TODO statt die letzte szene zu laden muessen wir nun eigentlich nur noch die Map (das terrain laden/speichern)
      // this.loadScene(loadEvent.getPath());
      return true;
    }
    if (event.getType().equalsIgnoreCase("SAVE")) {
      final SaveEvent saveEvent = (SaveEvent) event;
      this.saveScene(saveEvent.getPath());
      return true;
    }
    return false;
  }

  @Deprecated
  public void loadScene(final String filepath) {
    if (new File(filepath).exists()) {
      System.out.println("Found file.save. Try to load the last scene ...");
      final BinaryImporter imp = BinaryImporter.getInstance();
      imp.setAssetManager(bloxelApplication.getAssetManager());
      try {
        final Node loadedBloxelsNode = (Node) imp.load(new FileInputStream("scene.save"));
        final Node bloxelsNode = bloxelApplication.getBloxelsNode();
        final ArrayList<Spatial> currentBloxels = new ArrayList<Spatial>(bloxelsNode.getChildren());
        // for (final Spatial spatial : currentBloxels) {
        // bloxelApplication.removeBloxel((Bloxel) spatial);
        // }
        // for (final Spatial spatial : new ArrayList<Spatial>(loadedBloxelsNode.getChildren())) {
        // bloxelApplication.addBloxel(spatial);
        // }
      } catch (final NullPointerException e) {
        // XXX only a workaround ... if the file is corrupt jme throws a NPE
        LOG.error("Unable to read savefile '{}'", filepath, e);
      } catch (final IOException e) {
        LOG.error("Unable to read savefile '{}'", filepath, e);
      }
    }
  }

  @Deprecated
  public void saveScene(final String filepath) {
    try {
      BinaryExporter.getInstance().save(bloxelApplication.getBloxelsNode(), new File(filepath));
    } catch (final IOException e) {
      LOG.error("Unable to write savefile '%s'", filepath, e);
    }
  }
}